export interface CarItemState {
	url: string
	title: string
	desc: string
	id: number
	price: number
	count: number
	isCheck: boolean
}

export interface State {
	car: CarItemState[]
}

const initState: State = {
	car: JSON.parse(localStorage.getItem('car') || '[]') || []
}

const ADD_CAR_ITEM = 'ADD_CAR_ITEM'
const CHANGE_CAR_ITEM = 'CHANGE_CAR_ITEM'
const SWITCH_CAR_ITEM_CHECK = 'SWITCH_CAR_ITEM_CHECK'
const CHNAGE_SWITCH_ALL = 'CHNAGE_SWITCH_ALL'
const DELETE_CAR_ITEM = 'DELETE_CAR_ITEM'

interface AddCarItemType {
	type: typeof ADD_CAR_ITEM
	payload: CarItemState
}

interface ChangeCarItemType {
	type: typeof CHANGE_CAR_ITEM
	payload: { id: number, count: number }
}

interface SwitchCarItemCheck {
	type: typeof SWITCH_CAR_ITEM_CHECK
	payload: { id: number }
}

interface ChangeSwitchAll {
	type: typeof CHNAGE_SWITCH_ALL
	payload: boolean
}

interface DeleteCarItem {
	type: typeof DELETE_CAR_ITEM
	payload: number
}

export function addCarItemCreateAction(payload: CarItemState): AddCarItemType {
	return { type: ADD_CAR_ITEM, payload  }
}

export function chnageCarItemCreateAction(payload: { id: number, count: number }): ChangeCarItemType {
	return { type: CHANGE_CAR_ITEM, payload  }
}

export function switchCarItemCheckCreateAction(payload: { id: number }): SwitchCarItemCheck {
	return { type: SWITCH_CAR_ITEM_CHECK, payload  }
}

export function changeSwitchAllCreateAction(payload: boolean):ChangeSwitchAll  {
	return { type: CHNAGE_SWITCH_ALL, payload }
}	

export function deleteCarItem(payload: number):DeleteCarItem  {
	return { type: DELETE_CAR_ITEM, payload }
}



type ActionTypes = AddCarItemType | ChangeCarItemType | SwitchCarItemCheck | ChangeSwitchAll | DeleteCarItem

const carReducer = (state = initState, action: ActionTypes) => {
	switch (action.type) {
		case ADD_CAR_ITEM:
			{
				const item = state.car.find(v => v.id === action.payload.id)

				if(item) {
					item.count += action.payload.count;
					return {
						...state,
						car: [...state.car]
					}
				} else {
					return {
						...state,
						car: [...state.car, action.payload]
					}
				};
			}
		case CHANGE_CAR_ITEM:
			{
				const item = state.car.find(v => v.id === action.payload.id)

				if(item) {
					item.count = action.payload.count
				}

				return {
					...state,
					car: [...state.car]
				}
			}
		case SWITCH_CAR_ITEM_CHECK:
			{
				const item = state.car.find(v => v.id === action.payload.id);
				if(item) {
					item.isCheck = !item.isCheck 
				}
				return {
					...state,
					car: [...state.car]
				}
			}
		case CHNAGE_SWITCH_ALL:
			return {
				...state,
				car: [...state.car].map(v => {
					v.isCheck = action.payload;
					return v
				})
			}
		case DELETE_CAR_ITEM:
			return {
				...state,
				car: [...state.car].filter(v => v.id !== action.payload)
			}
		default:
			return state
	}
}


export default carReducer